package ca.etsmtl.log430.lab3;

import java.util.List;
import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class StateSortFilter extends Thread {

	// Declarations

	boolean done;

	PipedReader inputPipe = new PipedReader();
	PipedWriter outputPipe = new PipedWriter();

	public StateSortFilter(PipedWriter inputPipe, PipedWriter outputPipe) {

		try {

			// Connect inputPipe
			this.inputPipe.connect(inputPipe);
			System.out.println("StateSortFilter:: connected to upstream filter.");

			// Connect OutputPipes

			this.outputPipe = outputPipe;
			System.out.println("StateSortFilter:: connected to downstream filter.");

		} catch (Exception Error) {

			System.out.println("StateSortFilter:: Error connecting to other filters.");

		} // try/catch

	} // Constructor

	// This is the method that is called when the thread is started

	public void run() {

		// Declarations

		char[] characterValue = new char[1];
		// char array is required to turn char into a string
		String lineOfText = "";
		// string is required to look for the status code
		int integerCharacter; // the integer value read from the pipe

		List<String> inputlines = new ArrayList<String>();

		try {

			done = false;

			while (!done) {

				integerCharacter = inputPipe.read();
				characterValue[0] = (char) integerCharacter;

				if (integerCharacter == -1) { // pipe is closed

					done = true;

				} else {

					if (integerCharacter == '\n') { // end of line

						if(lineOfText.length() > 0 ) {
							inputlines.add(lineOfText);
							System.out.println("StateSortFilter:: Received: " + lineOfText + "on input pipe.");
						}

						lineOfText = "";
					} else {

						lineOfText += new String(characterValue);

					} // if //

				} // if

			} // while

		} catch (Exception error) {

			System.out.println("StateSortFilter:: Interrupted.");

		} // try/catch

		//sorting
		Collections.sort(inputlines, new Comparator<String>() {
			
			@Override
			public int compare(String o1, String o2) {
				return o1.split(" ")[5].compareTo(o2.split(" ")[5]);
			}
		});

		for (String string : inputlines) {
			try {
				outputPipe.write(string + "\n", 0, string.length()+1);
				System.out.println("StateSortFilter:: Writing: " + string + " on output pipe.");
				outputPipe.flush(); 
			} catch (Exception error) {
				System.out.println("StateSortFilter:: Interrupted.");
			}
		}

		try {

			inputPipe.close();
			System.out.println("StateSortFilter:: input pipe closed.");

			outputPipe.close();
			System.out.println("StateSortFilter:: output pipe closed.");

		} catch (Exception Error) {

			System.out.println("StateSortFilter:: Error closing pipes.");

		} // try/catch

	} // run

} // class